<?php


namespace App\Jobs\QiPao;

use App\Jobs\Job;
use App\Enums\ExportEnum;

class ExcelJob extends Job
{
    protected $admin_id;         //管理员id
    protected $data_no;          //导出数据编号  app/enum/ExportEnum 中
    protected $condition;        //查询条件
    protected $exportLogId;      //导出表格id
    //    const jobName = 'manager_excel';
    protected $funName;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    /**
     * ExcelJob constructor.
     *
     * @param $admin_export_log_id 纪录id
     * @param $admin_id 当前管理员id
     * @param $data_no 导出数据编号  app/enum/ExportEnum 中
     * @param $condition 筛选条件
     */
    public function __construct($admin_export_log_id, $admin_id, $data_no, $condition)
    {
        $this->exportLogId = $admin_export_log_id;
        $this->admin_id = $admin_id;
        $this->data_no = $data_no;
        $this->condition = $condition;
        $this->funName = ExportEnum::NO[$data_no]['get_data_fun'];
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $functionName = $this->funName;
        $data = [
            'admin_id'     => $this->admin_id ?? '',
            'data_no'      => $this->data_no ?? 0,
            'condition'    => json_encode($this->condition) ?? '',
            'status'       => 0,//正在导出
            'download_url' => '',
        ];
        $log = app('model_admin_export_log')->where('id', $this->exportLogId)->where('status', 0)->get();
        if (!$log) {//没有导出日志
            return false;
        }
        try {
            if (!empty($functionName)) {
                ini_set('memory_limit', '512M');
                app('repo_get_data_to_excel')->rmDir(storage_path('excel'));                               //清空excel临时文件夹
                $res = app('repo_get_data_to_excel')->$functionName(json_decode($data['condition'], true));//函数内实现分页查询 分页导入excel 返回值必须是
                if ($res) {
                    app('model_admin_export_log')->where('id', $this->exportLogId)->update(['status' => 1, 'download_url' => $res]);//导出成功
                } else {
                    app('model_admin_export_log')->where('id', $this->exportLogId)->update(['status' => 2]);
                }
            }
        } catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg'  => $e->getMessage(),
            ];
        }
        app('model_admin_export_log')->where('id', $this->exportLogId)->update(['status' => 1, 'download_url' => $res]);                      // 标记导出程序完毕
    }
}